package com.ht.api.call.impl;

import com.ht.api.db.*;
import org.springframework.stereotype.Component;

import com.ht.api.bean.AjaxResult;
import com.ht.api.bean.LoginBean;
import com.ht.api.call.AbstractCall;

import cn.hutool.json.JSONObject;

import javax.sql.DataSource;

/**
 * 业务执行器:query
 * @author asq
 * @createTime 2024年12月23日 21:02:18
 */
@Component
public class QueryCall extends AbstractCall {
	
	@Override
	public boolean isOpen() {
		return false;
	}

	@Override
	public String getName() {
		return "通用查询";
	}

	@Override
	public AjaxResult doExecute(LoginBean me, JSONObject param, JSONObject config) {
		DataSource ds = null;
		if (me.isSysCommonCall()) {
			ds = DbConfig.useSysDb();
		} else {
			ds = me.getDataSource();
		}


		String table = config.getStr("table");
		SqlParser sql = param.getBean(PARAM, SqlParser.class).setTable(table);
		
		// 添加默认排序
		if (!sql.containsKey(SqlParser.ORDER)) {
			if ("db_table".equals(table) || "db_column".equals(table)) {
				sql.order("order_num", "desc").order("sys_time", "asc").order("main_id", "asc");
				
				// 排除db_table的元数据
				String field = "db_table".equals(table) ? "code" : "table_code";
				sql.where(field, "!=", "db_table");
				sql.where(field, "!=", "db_column");
			} else {
				sql.order("sys_creator", "desc").order("sys_time", "desc").order("main_id", "desc");
			}
		}
		
		return AjaxResult.success().put(DATA, DbPage.create(ds, sql));
	}
}
